import request from "@/utils/request";
import {LoginData} from "./model";
import ApiResult from "@/typings/global";
import {doEncryptBySM2} from "@/utils/smUtils";
import {X_KEY_SM2} from "@/enums/CacheEnum";

class AuthAPI {
    /**
     * 登录API
     *
     * @param data {LoginData}
     * @returns
     */
    static login(data: LoginData) {
        const formData = new FormData();
        let puk = sessionStorage.getItem(X_KEY_SM2);
        formData.append("loginWay", data.loginWay);
        if (data.loginWay === 'account') {
            formData.append("username", doEncryptBySM2(puk, data.username));
            formData.append("password", doEncryptBySM2(puk, data.password));
            formData.append("randomStr", data.randomStr || "");
            formData.append("captcha", data.captcha || "");
        } else {
            formData.append("randomStr", data.randomStr || "");
            formData.append("areaCode", data.areaCode || "");
            formData.append("phoneNumber", doEncryptBySM2(puk, data.phoneNumber));
            formData.append("verificationCode", data.verificationCode);
            formData.append("phoneUserId", data.phoneUserId);
        }

        return request<any, ApiResult>({
            url: "/login",
            method: "post",
            data: formData,
            headers: {
                "Content-Type": "multipart/form-data",
            },
        });
    }

    /**
     * 注销API
     */
    static logout() {
        return request({
            url: "/logout",
            method: "post",
        });
    }

    /**
     * 获取验证码
     */
    static getCaptcha(randomStr: string) {
        return request<any, ApiResult>({
            url: "/api/auth/captcha?randomStr=" + randomStr,
            method: "get",
        });
    }

    static sendSMS(randomStr: string | undefined | null, phoneNumber: string) {
        let puk = sessionStorage.getItem(X_KEY_SM2);
        let phoneNumberEnc = doEncryptBySM2(puk, phoneNumber)
        return request<any, ApiResult>({
            url: "/api/auth/sendSMS",
            method: "post",
            data: {randomStr: randomStr, phoneNumber: phoneNumberEnc},
            headers: {
                'F-Pre-RandomStr': randomStr
            }
        });
    }

    static smsCheck(randomStr: string | undefined | null, phoneNumber: string, verificationCode: string) {
        let puk = sessionStorage.getItem(X_KEY_SM2);
        let phoneNumberEnc = doEncryptBySM2(puk, phoneNumber)
        return request<any, ApiResult>({
            url: "/api/auth/smsCheck",
            method: "post",
            data: {randomStr: randomStr, phoneNumber: phoneNumberEnc, verificationCode: verificationCode},
            headers: {
                'F-Pre-RandomStr': randomStr
            }
        });
    }
}

export default AuthAPI;
